<?php
// +----------------------------------------------------------------------
// | NewThink [ Think More,Think Better! ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2019 http://www.newthink.cc All rights reserved.
// +----------------------------------------------------------------------
// | 版权所有：山西创泰网络科技有限公司
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\common\service\airquality\AirQualityStationAqiRealtimeDayService;
use app\common\validate\airQuality\AirQualityWeatherAnalysisValidate;
use think\Db;
use think\Request;
use think\facade\Config;
use app\common\service\CommonService;

header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");

/**
 * 空气质量预报 - 气象分析
 */
class AirQualityWeatherAnalysis extends BaseController
{
    protected $validates;
    protected $airQualityStationAqiRealtimeDay;
    public function __construct()
    {
        $this->validates                       = new AirQualityWeatherAnalysisValidate();
        $this->airQualityStationAqiRealtimeDay = new AirQualityStationAqiRealtimeDayService();
    }

    /**
     * 气象分析左侧表格数据
     * @author yy by 2019/3/21
     */
    public function getAirQualityWeatherAnalysisTable()
    {
        $param    = request()->param();
        # 模拟数据
//        $param  = ['start_time' => '2019-04', 'end_time' => '2019-05', 'region_id'=>53, 'station_id' => 1, 'date_type' => 'month'];
//        $param  = ['start_time' => '2019', 'end_time' => '2019', 'region_id'=>53, 'station_id' => 1, 'date_type' => 'year'];
//        $param  = ['start_time' => '2019-05-25', 'end_time' => '2019-05-29', 'region_id'=>53, 'station_id' => 1, 'date_type' => 'day'];
        $result =  $this->validates->check($param, [], 'airQualityWeatherAnalysis');
        if (!$result) {
            $this->error( $this->validates->getError());
        }
        $list = [];
        try {
            $list = $this->airQualityStationAqiRealtimeDay->getTable($param);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('成功', $list);
    }

    public function a()
    {
        $param    = request()->param();
        # 模拟数据
        $param  = ['start_time' => '2019-05-22', 'end_time' => '2019-05-23', 'region_id'=>53, 'station_id' => 1,'date_type' => 'day'];
        $result =  $this->validates->check($param, [], 'airQualityWeatherAnalysis');
        if (!$result) {
            $this->error( $this->validates->getError());
        }
        $list = [];
        try {
            $list = $this->airQualityStationAqiRealtimeDay->getTable($param);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('成功', $list);
    }

    /**
     * 气象对应空气质量占比
     * @author yy by 2019/3/28
     */
    public function getAirQualityRate()
    {

    }

    /**
     * 首要污染物占比(轻度，中度，重度，严重)
     * 当前进入页面默认为轻度下的占比
     * 页面变动，暂时搁置 TODO
     * @author yy by 2019/4/3
     */
    public function getPrimaryPollutantRate()
    {
//        $param  = $this->request->param();
        #模拟数据
        $param  = ['start_time' => '2019-02', 'end_time' => '2019-04', 'station_id' => 1, 'date_type' => 'month','aqi_level'=>'严重'];
        $result = $this->validates->check($param, [], 'primaryPollutantRate');
        if (!$result) {
            $this->error($this->validates->getError());
        }
        $list = [];
        try {
            $list = $this->airQualityStationAqiRealtimeDay->getPrimaryPollutantRate($param);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
//        $this->success('成功', $list);
    }

    /**
     * 优良条件下的六参平均值
     * 页面变动，暂时搁置 TODO
     * @author yy by 2019/4/3
     */
    public function getSixParamAverage()
    {
//        $param  = $this->request->param();
        #模拟数据
        $param  = ['start_time' => '2019-02', 'end_time' => '2019-04', 'station_id' => 1, 'date_type' => 'month','aqi_level'=>'严重'];
        $result = $this->validates->check($param, [], 'primaryPollutantRate');
        if (!$result) {
            $this->error($this->validates->getError());
        }
        $list = [];
        try {
            $list = $this->airQualityStationAqiRealtimeDay->getSixParamAverage($param);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
//        $this->success('成功', $list);
    }


    /**
     * 空气质量频次图
     * zhugeng 2019-06-21
     */
    public function airQualityFrequency(){
        $param    = request()->param();
        $data = [];
        if (empty($param['type']) || empty($param['start_time']) || empty($param['end_time'])) {
            $this->error('参数错误');
        }
        if ($param['type'] == 'day') {
        } elseif ($param['type'] == 'month') {
            $param['start_time'] = date('Y-m-01',strtotime($param['start_time']));//所选月份的第一天
            if (date('Y-m',strtotime($param['end_time'])) == date('Y-m',time())) {
                $param['end_time'] = date('Y-m-d',strtotime("-1 day"));//昨天
            } else {
                $param['end_time'] = self::getthemonth($param['end_time']);//所选月份的最后一天
            }

        } else {
            $param['start_time'] = date('Y-01-01',strtotime($param['start_time']));//所选年的第一月第一天
            if (date('Y',strtotime($param['end_time'])) == date('Y',time())) {
                $param['end_time'] = date('Y-m-d',strtotime("-1 day"));//昨天
            } else {
                $param['end_time'] = date('Y-12-31',strtotime($param['start_time']));//所选年的最后一月的最后一天
            }

        }
        //实际
        $sql = 'select aqi_day,stable_weather_index_value,publish_time from stable_weather_index_realtime_day_new where station_id = ? and publish_time between ? and ? and publish_time = predict_time';
        $list = Db::query($sql,array($param['station_id'],$param['start_time'],$param['end_time']));        if (count($list) <= 0) {
           $data[0] = [];
        } else {
            $num_a1 = 0;$num_a2 = 0;$num_a3 = 0;$num_a4 = 0;$num_a5 = 0;$num_a6 = 0;
            $num_b1 = 0;$num_b2 = 0;$num_b3 = 0;$num_b4 = 0;$num_b5 = 0;$num_b6 = 0;
            $num_c1 = 0;$num_c2 = 0;$num_c3 = 0;$num_c4 = 0;$num_c5 = 0;$num_c6 = 0;
            $num_d1 = 0;$num_d2 = 0;$num_d3 = 0;$num_d4 = 0;$num_d5 = 0;$num_d6 = 0;
            $num_e1 = 0;$num_e2 = 0;$num_e3 = 0;$num_e4 = 0;$num_e5 = 0;$num_e6 = 0;
            foreach ($list as $k => $v) {
                if ($v['stable_weather_index_value'] > 0 && $v['stable_weather_index_value'] <= 5) {
                    if ($v['aqi_day'] > 0 && $v['aqi_day'] <= 50) {
                        $num_a1 += 1;
                    } elseif ($v['aqi_day'] > 50 && $v['aqi_day'] <= 100) {
                        $num_a2 += 1;
                    } elseif ($v['aqi_day'] > 100 && $v['aqi_day'] <= 150) {
                        $num_a3 += 1;
                    } elseif ($v['aqi_day'] > 150 && $v['aqi_day'] <= 200) {
                        $num_a4 += 1;
                    } elseif ($v['aqi_day'] > 200 && $v['aqi_day'] <= 300) {
                        $num_a5 += 1;
                    } elseif ($v['aqi_day'] > 300) {
                        $num_a6 += 1;
                    }
                } elseif ($v['stable_weather_index_value'] > 5 && $v['stable_weather_index_value'] <= 10) {
                    if ($v['aqi_day'] > 0 && $v['aqi_day'] <= 50) {
                        $num_b1 += 1;
                    } elseif ($v['aqi_day'] > 50 && $v['aqi_day'] <= 100) {
                        $num_b2 += 1;
                    } elseif ($v['aqi_day'] > 100 && $v['aqi_day'] <= 150) {
                        $num_b3 += 1;
                    } elseif ($v['aqi_day'] > 150 && $v['aqi_day'] <= 200) {
                        $num_b4 += 1;
                    } elseif ($v['aqi_day'] > 200 && $v['aqi_day'] <= 300) {
                        $num_b5 += 1;
                    } elseif ($v['aqi_day'] > 300){
                        $num_b6 += 1;
                    }

                } elseif ($v['stable_weather_index_value'] > 10 && $v['stable_weather_index_value'] <= 15) {
                    if ($v['aqi_day'] > 0 && $v['aqi_day'] <= 50) {
                        $num_c1 += 1;
                    } elseif ($v['aqi_day'] > 50 && $v['aqi_day'] <= 100) {
                        $num_c2 += 1;
                    } elseif ($v['aqi_day'] > 100 && $v['aqi_day'] <= 150) {
                        $num_c3 += 1;
                    } elseif ($v['aqi_day'] > 150 && $v['aqi_day'] <= 200) {
                        $num_c4 += 1;
                    } elseif ($v['aqi_day'] > 200 && $v['aqi_day'] <= 300) {
                        $num_c5 += 1;
                    } elseif ($v['aqi_day'] > 300) {
                        $num_c6 += 1;
                    }
                } elseif ($v['stable_weather_index_value'] > 15 && $v['stable_weather_index_value'] <= 20) {
                    if ($v['aqi_day'] > 0 && $v['aqi_day'] <= 50) {
                        $num_d1 += 1;
                    } elseif ($v['aqi_day'] > 50 && $v['aqi_day'] <= 100) {
                        $num_d2 += 1;
                    } elseif ($v['aqi_day'] > 100 && $v['aqi_day'] <= 150) {
                        $num_d3 += 1;
                    } elseif ($v['aqi_day'] > 150 && $v['aqi_day'] <= 200) {
                        $num_d4 += 1;
                    } elseif ($v['aqi_day'] > 200 && $v['aqi_day'] <= 300) {
                        $num_d5 += 1;
                    } elseif ($v['aqi_day'] > 300) {
                        $num_d6 += 1;
                    }
                } else {
                    if ($v['aqi_day'] > 0 && $v['aqi_day'] <= 50) {
                        $num_e1 += 1;
                    } elseif ($v['aqi_day'] > 50 && $v['aqi_day'] <= 100) {
                        $num_e2 += 1;
                    } elseif ($v['aqi_day'] > 100 && $v['aqi_day'] <= 150) {
                        $num_e3 += 1;
                    } elseif ($v['aqi_day'] > 150 && $v['aqi_day'] <= 200) {
                        $num_e4 += 1;
                    } elseif ($v['aqi_day'] > 200 && $v['aqi_day'] <= 300) {
                        $num_e5 += 1;
                    } elseif ($v['aqi_day'] > 300) {
                        $num_e6 += 1;
                    }
                }
            }
            $data[0] = [5,50,$num_a1];
            $data[1] = [5,100,$num_a2];
            $data[2] = [5,150,$num_a3];
            $data[3] = [5,200,$num_a4];
            $data[4] = [5,300,$num_a5];
            $data[5] = [5,500,$num_a6];//TODO 待定
            $data[6] = [10,50,$num_b1];
            $data[7] = [10,100,$num_b2];
            $data[8] = [10,150,$num_b3];
            $data[9] = [10,200,$num_b4];
            $data[10] = [10,300,$num_b5];
            $data[11] = [10,500,$num_b6];//TODO 待定
            $data[12] = [15,50,$num_c1];
            $data[13] = [15,100,$num_c2];
            $data[14] = [15,150,$num_c3];
            $data[15] = [15,200,$num_c4];
            $data[16] = [15,300,$num_c5];
            $data[17] = [15,500,$num_c6];//TODO 待定
            $data[18] = [20,50,$num_d1];
            $data[19] = [20,100,$num_d2];
            $data[20] = [20,150,$num_d3];
            $data[21] = [20,200,$num_d4];
            $data[22] = [20,300,$num_d5];
            $data[23] = [20,500,$num_d6];//TODO 待定
            $data[24] = [50,50,$num_e1];//TODO 待定
            $data[25] = [50,100,$num_e2];//TODO 待定
            $data[26] = [50,150,$num_e3];//TODO 待定
            $data[27] = [50,200,$num_e4];//TODO 待定
            $data[28] = [50,300,$num_e5];//TODO 待定
            $data[29] = [50,500,$num_e6];//TODO 待定

        }
        $this->success('成功',$data);
    }

    /**
     * 静稳指数分布
     * zhugeng 2019-06-21
     */
    public function calmIndex(){
        $param = request()->param();
        $data = [];
        if (empty($param['type']) || empty($param['start_time']) || empty($param['end_time'])) {
            $this->error('参数错误');
        }
        if ($param['type'] == 'day') {
        } elseif ($param['type'] == 'month') {
            $param['start_time'] = date('Y-m-01',strtotime($param['start_time']));//所选月份的第一天
            if (date('Y-m',strtotime($param['end_time'])) == date('Y-m',time())) {
                $param['end_time'] = date('Y-m-d',strtotime("-1 day"));//昨天
            } else {
                $param['end_time'] = self::getthemonth($param['end_time']);//所选月份的最后一天
            }

        } else {
            $param['start_time'] = date('Y-01-01',strtotime($param['start_time']));//所选年的第一月第一天
            if (date('Y',strtotime($param['end_time'])) == date('Y',time())) {
                $param['end_time'] = date('Y-m-d',strtotime("-1 day"));//昨天
            } else {
                $param['end_time'] = date('Y-12-31',strtotime($param['start_time']));//所选年的最后一月的最后一天
            }
        }
        //实际
        $sql = 'select stable_weather_index_value,publish_time from stable_weather_index_realtime_day_new where station_id = ? and publish_time between ? and ? and publish_time = predict_time';
        $list = Db::query($sql,array($param['station_id'],$param['start_time'],$param['end_time']));
        if (count($list) <= 0) {
            $data[0] = [];
        } else {
            $num_a1 = 0;$num_a2 = 0;$num_a3 = 0;$num_a4 = 0;$num_a5 = 0;
            $num_b1 = [];$num_b2 = [];$num_b3 = [];$num_b4 = [];$num_b5 = [];
            foreach ($list as $k => $v) {
                if ($v['stable_weather_index_value'] > 0 && $v['stable_weather_index_value'] <= 5) {
                    $num_a1 += 1;
                    if ($param['type'] == 'day') {
                        $num_b1[] = date('Y-m-d',strtotime($v['publish_time']));
                    } else {
                        $num_b1[] = date('Y-m-d',strtotime($v['publish_time']));
                    }

                } elseif ($v['stable_weather_index_value'] > 5 && $v['stable_weather_index_value'] <= 10) {
                    $num_a2 += 1;
                    if ($param['type'] == 'day') {
                        $num_b2[] = date('Y-m-d',strtotime($v['publish_time']));
                    } else {
                        $num_b2[] = date('Y-m-d',strtotime($v['publish_time']));
                    }

                } elseif ($v['stable_weather_index_value'] > 10 && $v['stable_weather_index_value'] <= 15) {
                    $num_a3 += 1;
                    if ($param['type'] == 'day') {
                        $num_b3[] = date('Y-m-d',strtotime($v['publish_time']));
                    } else {
                        $num_b3[] = date('Y-m-d',strtotime($v['publish_time']));
                    }

                } elseif ($v['stable_weather_index_value'] > 15 && $v['stable_weather_index_value'] <= 20) {
                    $num_a4 += 1;
                    if ($param['type'] == 'day') {
                        $num_b4[] = date('Y-m-d',strtotime($v['publish_time']));
                    } else {
                        $num_b4[] = date('Y-m-d',strtotime($v['publish_time']));
                    }

                } elseif ($v['stable_weather_index_value'] > 20) {
                    $num_a5 += 1;
                    if ($param['type'] == 'day') {
                        $num_b5[] = date('Y-m-d',strtotime($v['publish_time']));
                    } else {
                        $num_b5[] = date('Y-m-d',strtotime($v['publish_time']));
                    }

                }
            }

            $data = [
                ['name'=>'0~5','value'=>$num_a1,'time'=>implode(',',$num_b1)],
                ['name'=>'5~10','value'=>$num_a2,'time'=>implode(',',$num_b2)],
                ['name'=>'10~15','value'=>$num_a3,'time'=>implode(',',$num_b3)],
                ['name'=>'15~20','value'=>$num_a4,'time'=>implode(',',$num_b4)],
                ['name'=>'20以上','value'=>$num_a5,'time'=>implode(',',$num_b5)]
            ];

        }
        $this->success('成功',$data);
    }

    /**
     * 气象对应空气质量占比
     * zhugeng 2019-06-21
     */
    public function airQualityProportion(){
        $param = request()->param();
        if (empty($param['type'])) {
            $this->error('参数错误');
        }
        if ($param['time'] == '') {
            $data = [
                ['name'=>'优','value'=>0,'time'=>''],
                ['name'=>'良','value'=>0,'time'=>''],
                ['name'=>'轻度','value'=>0,'time'=>''],
                ['name'=>'中度','value'=>0,'time'=>''],
                ['name'=>'重度','value'=>0,'time'=>''],
                ['name'=>'严重','value'=>0,'time'=>'']
            ];
        } else {
            $time = explode(',',$param['time']);
            $num_a1 = 0;$num_a2 = 0;$num_a3 = 0;$num_a4 = 0;$num_a5 = 0;$num_a6 = 0;
            $num_b1 = [];$num_b2 = [];$num_b3 = [];$num_b4 = [];$num_b5 = [];$num_b6 = [];
            foreach ($time as $k => $v) {
                $aqi = "select aqi_level from air_quality_station_aqi_realtime_day where station_id = ".$param['station_id']." and publish_time = '".$v."'";
                $result = Db::query($aqi);
                if (!empty($result)) {
                    if ($result[0]['aqi_level'] == '优') {
                        $num_a1 +=1;
                        $num_b1[] = $v;
                    } elseif ($result[0]['aqi_level'] == '良') {
                        $num_a2 +=1;
                        $num_b2[] = $v;
                    } elseif ($result[0]['aqi_level'] == '轻度') {
                        $num_a3 +=1;
                        $num_b3[] = $v;
                    } elseif ($result[0]['aqi_level'] == '中度') {
                        $num_a4 +=1;
                        $num_b4[] = $v;
                    } elseif ($result[0]['aqi_level'] == '重度') {
                        $num_a5 +=1;
                        $num_b5[] = $v;
                    } else {
                        $num_a6 +=1;
                        $num_b6[] = $v;
                    }
                }
            }
            $data = [
                ['name'=>'优','value'=>$num_a1,'time'=>implode(',',$num_b1)],
                ['name'=>'良','value'=>$num_a2,'time'=>implode(',',$num_b2)],
                ['name'=>'轻度','value'=>$num_a3,'time'=>implode(',',$num_b3)],
                ['name'=>'中度','value'=>$num_a4,'time'=>implode(',',$num_b4)],
                ['name'=>'重度','value'=>$num_a5,'time'=>implode(',',$num_b5)],
                ['name'=>'严重','value'=>$num_a6,'time'=>implode(',',$num_b6)]
            ];
        }
        $this->success('成功',$data);
    }


    /**
     * 六参平均值
     * zhugeng 2019-06-21
     */
    public function pollutantAverage(){
        $param = request()->param();
        if (empty($param['type'])) {
            $this->error('参数错误');
        }
        $time = explode(',',$param['time']);
        $result = [];
        $data = [];
        $data['date'] = ['PM2.5','PM10','SO2','NO2','CO','O3'];
        if (empty($param['time'])) {
            $data['data'][0] = [0,0,0,0,0,0];
        } else {
            foreach ($time as $k => $v) {
                $aqi = 'select pm25,pm10,so2,no2,co,o3 from air_quality_station_aqi_realtime_day where station_id = ? and publish_time = ?';
                $list = Db::query($aqi,array($param['station_id'],$v));
                if (!empty($list)) {
                    $result[] = $list[0];
                }
            }
            $num = count($result);
            $pm25 = '';$pm10 = '';$so2 = '';$no2 = '';$co = '';$o3 = '';
            foreach ($result as $k => $v) {
                $pm25 += $v['pm25'];
                $pm10 += $v['pm10'];
                $so2 += $v['so2'];
                $no2 += $v['no2'];
                $co += $v['co'];
                $o3 += $v['o3'];
            }
            $data['data'][0] = [
                round($pm25/$num),
                round($pm10/$num),
                round($so2/$num),
                round($no2/$num),
                round($co/$num,1),
                round($o3/$num),
            ];
        }

        $this->success('成功',$data);
    }

    /**
     * 首要污染物占比
     * zhugeng 2019-06-26
     */
    public function pollutantProportion(){
        $param = request()->param();
        if (empty($param['type'])) {
            $this->error('参数错误');
        }
        if ($param['time'] == '') {
            $data = [
                ['name'=>'PM2.5','value'=>0,'time'=>''],
                ['name'=>'PM10','value'=>0,'time'=>''],
                ['name'=>'SO2','value'=>0,'time'=>''],
                ['name'=>'NO2','value'=>0,'time'=>''],
                ['name'=>'CO','value'=>0,'time'=>''],
                ['name'=>'O3','value'=>0,'time'=>'']
            ];
        } else {
            $time = explode(',',$param['time']);
            $num_a1 = 0;$num_a2 = 0;$num_a3 = 0;$num_a4 = 0;$num_a5 = 0;$num_a6 = 0;
            foreach ($time as $k => $v) {
                $aqi = 'select name from air_quality_station_primary_pollutant_realtime_day where station_id = ? and publish_time = ?';
                $result = Db::query($aqi,array($param['station_id'],$v));
                if (!empty($result)) {
                    if ($result[0]['name'] == 'PM2.5') {
                        $num_a1 +=1;
                    } elseif ($result[0]['name'] == 'PM10') {
                        $num_a2 +=1;
                    } elseif ($result[0]['name'] == 'SO2') {
                        $num_a3 +=1;
                    } elseif ($result[0]['name'] == 'NO2') {
                        $num_a4 +=1;
                    } elseif ($result[0]['name'] == 'CO' || $result[0]['name'] == 'O3_8H') {
                        $num_a5 +=1;
                    } else {
                        $num_a6 +=1;
                    }
                }
            }
            $data = [
                ['name'=>'PM2.5','value'=>$num_a1],
                ['name'=>'PM10','value'=>$num_a2],
                ['name'=>'SO2','value'=>$num_a3],
                ['name'=>'NO2','value'=>$num_a4],
                ['name'=>'CO','value'=>$num_a5],
                ['name'=>'O3','value'=>$num_a6]
            ];
        }
        $this->success('成功',$data);
    }

    /**
     * 首要污染物趋势图(接口1)
     * zhugeng 2019-06-26
     */
    public function pollutantChart(){
        $param = request()->param();
        if (empty($param['type']) || empty($param['pollutant'])) {
            $this->error('参数错误');
        }

        if ($param['type'] == 'day') {
        } elseif ($param['type'] == 'month') {
            $param['start_time'] = date('Y-m-01',strtotime($param['start_time']));//所选月份的第一天
            if (date('Y-m',strtotime($param['end_time'])) == date('Y-m',time())) {
                $param['end_time'] = date('Y-m-d',strtotime("-1 day"));//昨天
            } else {
                $param['end_time'] = self::getthemonth($param['end_time']);//所选月份的最后一天
            }

        } else {
            $param['start_time'] = date('Y-01-01',strtotime($param['start_time']));//所选年的第一月第一天
            if (date('Y',strtotime($param['end_time'])) == date('Y',time())) {
                $param['end_time'] = date('Y-m-d',strtotime("-1 day"));//昨天
            } else {
                $param['end_time'] = date('Y-12-31',strtotime($param['start_time']));//所选年的最后一月的最后一天
            }
        }
        $lastWeek = self::getDateFromRange($param['start_time'],$param['end_time']);
        $data['date'] = $lastWeek;
        //实际
        $sql = 'select value,publish_time from air_quality_station_primary_pollutant_realtime_day where station_id = ? and name = ? and publish_time between ? and ?';
        $list = Db::query($sql,array($param['station_id'],$param['pollutant'],$param['start_time'],$param['end_time']));
        if (count($list) <= 0) {
            foreach ($lastWeek as $k => $v) {
                $data['data'][0][$k] = '';
            }
        } else {
            $newDate = [];
            $newList2 = [];
            foreach ($list as $k => $v) {
                $newList2[date("m/d", strtotime($v['publish_time']))][] = $v['value'];
                array_push($newDate, date('m/d', strtotime($v['publish_time'])));
            }
            foreach ($lastWeek as $k => $v) {
                if (in_array($v,$newDate)) {
                    $data['data'][0][$k] = $newList2[$v][0];
                } else {
                    $data['data'][0][$k] = '';
                }
            }
        }
        $this->success('成功',$data);
    }
    /**
     * 首要污染物平均值(接口2)
     * zhugeng 2019-06-27
     */
    public function pollutantAvg(){
        $param = request()->param();
        if (empty($param['type']) || empty($param['pollutant'])) {
            $this->error('参数错误');
        }
        $data['date'] = [$param['pollutant']];
        if ($param['time'] == '') {
            $data['data'][] = [];
        } else {
            $time = explode(',',$param['time']);
            $num = count($time);
            $num_a1 = 0;
            foreach ($time as $k => $v) {
                $aqi = 'select value from air_quality_station_primary_pollutant_realtime_day where station_id = ? and name = ? and publish_time = ?';
                $result = Db::query($aqi,array($param['station_id'],$param['pollutant'],$v));
                if (!empty($result)) {
                    $num_a1 += $result[0]['value'];
                }
            }
            if ($param['pollutant'] == 'CO') {
                $avg = round($num_a1/$num,1);
            } else {
                $avg = round($num_a1/$num);
            }
            $data['data'][] = [$avg];
        }
        $this->success('成功',$data);
    }


    /**
     * 减排前贡献度平均值
     * zhugeng 2019-06-21
     */
    public function contributionAverage(){
        //链接MongoDB数据库（远程）
        $PDOManager = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        //本地
        //$this->PDOManager = new \MongoDB\Driver\Manager("mongodb://localhost:27017");
        $PDOBulk = new \MongoDB\Driver\BulkWrite;//插入
        $opt = [
            'projection' => [
                '_id' => 0
            ],
        ];
        $param = request()->param();
        $data = [];
        if (empty($param['region_id']) || empty($param['start_time']) || empty($param['end_time']) || empty($param['type'])) {
            $this->error('参数错误');
        }
        if ($param['type'] == 'day') {
        } elseif ($param['type'] == 'month') {
            $param['start_time'] = date('Y-m-01',strtotime($param['start_time']));//所选月份的第一天
            if (date('Y-m',strtotime($param['end_time'])) == date('Y-m',time())) {
                $param['end_time'] = date('Y-m-d',strtotime("-1 day"));//昨天
            } else {
                $param['end_time'] = self::getthemonth($param['end_time']);//所选月份的最后一天
            }

        } else {
            $param['start_time'] = date('Y-01-01',strtotime($param['start_time']));//所选年的第一月第一天
            if (date('Y',strtotime($param['end_time'])) == date('Y',time())) {
                $param['end_time'] = date('Y-m-d',strtotime("-1 day"));//昨天
            } else {
                $param['end_time'] = date('Y-12-31',strtotime($param['start_time']));//所选年的最后一月的最后一天
            }
        }
        //日期列表
        $lastYearWeek = self::getDateFromRange($param['start_time'], $param['end_time']);
        $num = count($lastYearWeek);
        $data['date'] = ['PM2.5','SO2','NOX'];
        //工业-----------------------------
        //条件参数
        $companyId = new CommonService();
        $map = [
            "region_id"     => (int)$param['region_id'],
            "station_id"    => (int)$param['station_id'],//站点
            "company_id"    => ['$lte' => $companyId->getCompanyLimitId()],
//            '$where'        => 'this.publish_time == this.predict_time',
//            'predict_time'  => ['$gte' => $param['start_time'].' 00:00:00', '$lte' => $param['end_time'].' 23:00:00']
        ];
        //通过日期判断是预测值还是实际值
        if (strtotime($param['end_time']) < strtotime(date('Y-m-d',time()))) {
            //实际值(上周或者过去时间段)
            $map['predict_time'] = [
                '$gte' => date('Y-m-d 00:00:00', strtotime($param['start_time'])),
                '$lte' => date('Y-m-d 23:00:00', strtotime($param['end_time']))
            ];
            $map['$where']       = 'this.publish_time == this.predict_time';
            //预报值
            $query  = new \MongoDB\Driver\Query($map, $opt);//查询
            $cursor = $PDOManager->executeQuery('huanxin.air_quality_pollutant_company_forecast_day', $query)->toArray();
            $list1   = json_decode(json_encode($cursor), true);
        } else {
            //计算今天到结束日期相差天数
            $days = $this->diffBetweenTwoDays($param['start_date'], date('Y-m-d')) + 1;
            if ($days > 1) {
                //实际+预报(本周或者今天日期在所选日期范围内)
                //实际
                $map['$where']       = 'this.publish_time == this.predict_time';
                $map['predict_time'] = [
                    '$gte' => date('Y-m-d 00:00:00', strtotime($param['start_time'])),
                    '$lte' => date('Y-m-d 23:00:00', strtotime('-1 day'))
                ];

                //实际值
                $query  = new \MongoDB\Driver\Query($map, $opt);//查询
                $cursor = $PDOManager->executeQuery('huanxin.air_quality_pollutant_company_forecast_day', $query)->toArray();
                $lista  = json_decode(json_encode($cursor), true);
                if (empty($lista)) {
                    $lista = [];
                }
                //预报（未来日期范围，包括今天）
                unset($map['$where']);
                $map['publish_time'] = date('Y-m-d ' . (date('H:i') < '14:20' ? '00' : '14') . ':00:00');
                $map['predict_time'] = [
                    '$gte' => date('Y-m-d 00:00:00'),
                    '$lte' => date("Y-m-d 23:00:00", strtotime($param['end_time']))
                ];
                //预报值
                $query  = new \MongoDB\Driver\Query($map, $opt);//查询
                $cursor = $PDOManager->executeQuery('huanxin.air_quality_pollutant_company_forecast_day', $query)->toArray();
                $listb  = json_decode(json_encode($cursor), true);
                if (empty($listb)) {
                    $listb = [];
                }
                $list1 = array_merge_recursive($lista, $listb);
            } else {
                $map['predict_time'] = [
                    '$gte' => date('Y-m-d 00:00:00'),
                    '$lte' => date('Y-m-d 23:00:00', strtotime($param['end_time']))
                ];
                $map['publish_time'] = date('Y-m-d ' . (date('H:i') < '14:20' ? '00' : '14') . ':00:00');
                //预报值
                $query  = new \MongoDB\Driver\Query($map, $opt);//查询
                $cursor = $PDOManager->executeQuery('huanxin.air_quality_pollutant_company_forecast_day', $query)->toArray();
                $list1   = json_decode(json_encode($cursor), true);
            }

        }
//        $query = new \MongoDB\Driver\Query($map, $opt);//查询
//        $cursor = $PDOManager->executeQuery('huanxin.air_quality_pollutant_company_forecast_day', $query)->toArray();
//        $list1 = json_decode(json_encode($cursor), true);
        $num_pm25 = 0;$num_so2 = 0;$num_no2 = 0;
        $concentration_pm25 = '';
        $concentration_so2 = '';
        $concentration_no2 = '';
        if (count($list1) <= 0) {
            $data['data'][0] = ['','',''];
        } else {
            $newList = [];
            foreach ($list1 as $k => $v) {
                $newList[date("Y-m-d", strtotime($v['predict_time']))][$v['contribution_name']][] = $v;
            }
            foreach ($newList as $k => $v) {
                if (isset($v['PM2.5'])) {
                    $concentration_pm25 += $v['PM2.5'][0]['concentration'];
                }
                if (isset($v['SO2'])) {
                    $concentration_so2  += $v['SO2'][0]['concentration'];
                }
                if (isset($v['NO2'])) {
                    $concentration_no2  += $v['NO2'][0]['concentration'];
                }
            }
            foreach ($list1 as $k => $v) {
                if ($v['contribution_name'] == 'PM2.5') {
                    $num_pm25 += $v['contribution_degree'];
                } elseif ($v['contribution_name'] == 'SO2') {
                    $num_so2 += $v['contribution_degree'];
                } else {
                    $num_no2 += $v['contribution_degree'];
                }
            }
            if (empty($concentration_pm25) && empty($num_pm25)) {
                $con_pm25 = 0;
            } else {
                $con_pm25 = round(($num_pm25/$concentration_pm25)*100,2);
            }
            if (empty($concentration_so2) && empty($num_so2)) {
                $con_so2 = 0;
            } else {
                $con_so2 = round(($num_so2/$concentration_so2)*100,2);
            }
            if (empty($concentration_no2) && empty($num_no2)) {
                $con_no2 = 0;
            } else {
                $con_no2 = round(($num_no2/$concentration_no2)*100,2);
            }
            $data['data'][0] = [
                $con_pm25,
                $con_so2,
                $con_no2,
            ];
        }
        //非工业-----------------------------
        //条件参数
        $map1 = [
//            "region_id"     => (int)$param['region_id'],
            "station_id"    => (int)$param['station_id'],//站点
//            "industry_id"   => ['$in' => Config::get('no_industry_limit_arr_mongodb')],
//            '$where'        => 'this.publish_time == this.predict_time',
//            'predict_time'  => ['$gte' => $param['start_time'].' 00:00:00', '$lte' => $param['end_time'].' 23:00:00']
        ];
        //通过日期判断是预测值还是实际值
        if (strtotime($param['end_time']) < strtotime(date('Y-m-d',time()))) {
            //实际值(上周或者过去时间段)
            $map1['predict_time'] = [
                '$gte' => date('Y-m-d 00:00:00', strtotime($param['start_time'])),
                '$lte' => date('Y-m-d 23:00:00', strtotime($param['end_time']))
            ];
            $map1['$where']       = 'this.publish_time == this.predict_time';
            //预报值
            $query  = new \MongoDB\Driver\Query($map1, $opt);//查询
            $cursor = $PDOManager->executeQuery('huanxin.air_quality_pollutant_non_industry_area_forecast_day', $query)->toArray();
            $list2   = json_decode(json_encode($cursor), true);
        } else {
            //计算今天到结束日期相差天数
            $days = $this->diffBetweenTwoDays($param['start_date'], date('Y-m-d')) + 1;
            if ($days > 1) {
                //实际+预报(本周或者今天日期在所选日期范围内)
                //实际
                $map1['$where']       = 'this.publish_time == this.predict_time';
                $map1['predict_time'] = [
                    '$gte' => date('Y-m-d 00:00:00', strtotime($param['start_time'])),
                    '$lte' => date('Y-m-d 23:00:00', strtotime('-1 day'))
                ];

                //实际值
                $query  = new \MongoDB\Driver\Query($map1, $opt);//查询
                $cursor = $PDOManager->executeQuery('huanxin.air_quality_pollutant_non_industry_area_forecast_day', $query)->toArray();
                $lista  = json_decode(json_encode($cursor), true);
                if (empty($lista)) {
                    $lista = [];
                }
                //预报（未来日期范围，包括今天）
                unset($map1['$where']);
                $map1['publish_time'] = date('Y-m-d ' . (date('H:i') < '14:20' ? '00' : '14') . ':00:00');
                $map1['predict_time'] = [
                    '$gte' => date('Y-m-d 00:00:00'),
                    '$lte' => date("Y-m-d 23:00:00", strtotime($param['end_time']))
                ];
                //预报值
                $query  = new \MongoDB\Driver\Query($map1, $opt);//查询
                $cursor = $PDOManager->executeQuery('huanxin.air_quality_pollutant_non_industry_area_forecast_day', $query)->toArray();
                $listb  = json_decode(json_encode($cursor), true);
                if (empty($listb)) {
                    $listb = [];
                }
                $list2 = array_merge_recursive($lista, $listb);
            } else {
                $map1['predict_time'] = [
                    '$gte' => date('Y-m-d 00:00:00'),
                    '$lte' => date('Y-m-d 23:00:00', strtotime($param['end_time']))
                ];
                $map1['publish_time'] = date('Y-m-d ' . (date('H:i') < '14:20' ? '00' : '14') . ':00:00');
                //预报值
                $query  = new \MongoDB\Driver\Query($map1, $opt);//查询
                $cursor = $PDOManager->executeQuery('huanxin.air_quality_pollutant_non_industry_area_forecast_day', $query)->toArray();
                $list2   = json_decode(json_encode($cursor), true);
            }

        }
//        $query = new \MongoDB\Driver\Query($map1, $opt);//查询
//        $cursor = $PDOManager->executeQuery('huanxin.air_quality_pollutant_non_industry_area_forecast_day', $query)->toArray();
//        $list2 = json_decode(json_encode($cursor), true);
        $nonum_pm25 = 0;$nonum_so2 = 0;$nonum_no2 = 0;
        $concentration_pm25_no = '';
        $concentration_so2_no = '';
        $concentration_no2_no = '';
        if (count($list2) <= 0) {
            $data['data'][1] = ['','',''];
        } else {
            $newList1 = [];
            foreach ($list2 as $k => $v) {
                $newList1[date("Y-m-d", strtotime($v['predict_time']))][$v['contribution_name']][] = $v;
            }
            foreach ($newList1 as $k => $v) {
                if (isset($v['PM2.5'])) {
                    $concentration_pm25_no += $v['PM2.5'][0]['concentration'];
                }
                if (isset($v['SO2'])) {
                    $concentration_so2_no  += $v['SO2'][0]['concentration'];
                }
                if(isset($v['NO2'])) {
                    $concentration_no2_no  += $v['NO2'][0]['concentration'];
                }
            }
            foreach ($list2 as $k => $v) {
                if ($v['contribution_name'] == 'PM2.5') {
                    $nonum_pm25 += $v['contribution_degree'];
                } elseif ($v['contribution_name'] == 'SO2') {
                    $nonum_so2 += $v['contribution_degree'];
                } else {
                    $nonum_no2 += $v['contribution_degree'];
                }
            }
            if (empty($concentration_pm25_no) && empty($nonum_pm25)) {
                $contribution_pm25 = 0;
            } else {
                $contribution_pm25 = round(($nonum_pm25/$concentration_pm25_no)*100,2);
            }
            if (empty($concentration_so2_no) && empty($nonum_so2)) {
                $contribution_so2 = 0;
            } else {
                $contribution_so2 = round(($nonum_so2/$concentration_so2_no)*100,2);
            }
            if (empty($concentration_no2_no) && empty($nonum_no2)) {
                $contribution_no2 = 0;
            } else {
                $contribution_no2 = round(($nonum_no2/$concentration_no2_no)*100,2);
            }
            $data['data'][1] = [
                $contribution_pm25,
                $contribution_so2,
                $contribution_no2,
            ];
        }
        $this->success('成功',$data);

    }




    /**
     * 获取指定日期段内每一天的日期(m/d)
     * @param  Date $startdate 开始日期
     * @param  Date $enddate 结束日期
     * @return Array
     */
    function getDateFromRange($startdate, $enddate)
    {
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);
        // 计算日期段内有多少天
        $days = ($etimestamp - $stimestamp) / 86400 + 1;
        // 保存每天日期
        $date = array();
        for ($i = 0; $i < $days; $i++) {
            $date[] = date('m/d', $stimestamp + (86400 * $i));
        }
        return $date;
    }

    /**
     * 获取指定日期段内每一天的日期(Y-m-d)
     * @param  Date $startdate 开始日期
     * @param  Date $enddate 结束日期
     * @return Array
     */
    public function getDateFromRangeYear($startdate, $enddate)
    {
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);
        // 计算日期段内有多少天
        $days = ($etimestamp - $stimestamp) / 86400 + 1;
        // 保存每天日期
        $date = array();
        for ($i = 0; $i < $days; $i++) {
            $date[] = date('Y-m-d', $stimestamp + (86400 * $i));
        }
        return $date;
    }
    /**
     * @param string $day1 开始日期
     * @param string $day2 结束日期
     * @return float|int 相差天数
     * @author zhugeng 2019-05-07
     */
    function diffBetweenTwoDays($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp     = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }
    //获取某个月的最后一天
    function getthemonth($date)
    {
        $firstday = date('Y-m-01', strtotime($date));
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
//        return array($firstday, $lastday);
        return $lastday;
    }
}